package com.doryar.girl.controller;

import com.doryar.girl.properties.BrowserSecurityProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
public class BrowserSecurityController {
     @Autowired
     private BrowserSecurityProperties browserSecurityProperties;
    //拿到发起请求的url
    private RequestCache requestCache=new HttpSessionRequestCache();
    //使用这个方法进行跳转
    private RedirectStrategy redirectStrategy=new DefaultRedirectStrategy();
    @RequestMapping("/authentication/require")
    @ResponseStatus(code= HttpStatus.UNAUTHORIZED)
   public simpleResponse requireAuthentication(HttpServletRequest request, HttpServletResponse response) throws IOException {
         SavedRequest savedRequest=requestCache.getRequest(request,response);
         if(savedRequest!=null)
         {
             String targetUrl=savedRequest.getRedirectUrl();
             if(StringUtils.endsWithIgnoreCase(targetUrl,".html")){
                redirectStrategy.sendRedirect(request,response,"/login.html");
             }
         }
        return new simpleResponse("请登录");
   }
}


